package com.haibei.activity.topic;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.ListUtiles;
import com.common.uitl.LogUtil;
import com.common.uitl.StringUtils;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.activity.BaseHaibeiActivity;
import com.haibei.activity.common.CommentActivity;
import com.haibei.activity.user.LoginActivity;
import com.haibei.adapter.CommentsAdapter;
import com.haibei.adapter.bean.Comment;
import com.haibei.adapter.bean.Topic;
import com.haibei.adapter.bean.User;
import com.haibei.net.NetInterface;
import com.haibei.view.AsnycImageView;
import com.haibei.view.SubTabViewTopic;
import com.haibei.view.xlist.XListView;
import com.haibei.view.xlist.XListView.IXListViewListener;

/**
 * 评论
 * @author wangzy
 */
public class TopicommentsActivity extends BaseHaibeiActivity implements IXListViewListener, View.OnClickListener {

	private ArrayList<Comment> mArrayList;
	private XListView listViewComments;
	private BaseTask mBaseTask;

	private final int page_size = 10;
	private final int INT_RTYPE_FIRST = 1;
	private final int INT_RTYPE_REFRESH = 2;
	private final int INT_RTYPE_LODMORE = 3;
	private final int INT_GO_COMMENT = 100;
	private final int INT_GO_REPLY = 101;

	private CommentsAdapter mAdapterConsult;
	private ArrayList<Comment> mListTemp;
	private PopupWindow mPop;
	private Comment mCommentCurrentReply;
	private Topic mTopic;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mTopic=(Topic) getIntent().getSerializableExtra("topic");
		mArrayList = new ArrayList<Comment>();
		mAdapterConsult = new CommentsAdapter(this, mArrayList);
		initView();
	}

	@Override
	public void initView() {
		setContentView(R.layout.activity_topic_comment);
		listViewComments = (XListView) findViewById(R.id.listViewComments);
		listViewComments.setXListViewListener(this);
		listViewComments.setPullLoadEnable(true);
		// listViewComments.addHeaderView(addHotComments(ConsultDetailActivity.hotelCommentList));//添加热门评论
		listViewComments.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Comment c = (Comment) parent.getAdapter().getItem(position);
				if (!StringUtils.isEmpty(c.getContent())) {
					createPopWin(view, c, (listViewComments.getLastVisiblePosition() == position));
				}
			}
		});

		findButtonById(R.id.buttonCancell).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		findButtonById(R.id.buttonBack).setOnClickListener(this);// 返回
		// findViewById(R.id.buttonHideReplay).setOnClickListener(this);// 隐藏回复
		findViewById(R.id.linearLayoutBottomReply).setOnClickListener(this);// 说两句
		requestComments(INT_RTYPE_FIRST, 0);
	}

	private void createPopWin(View v, final Comment c,boolean isBottom) {
		mCommentCurrentReply = c;
		final View pv = View.inflate(this, R.layout.pop_win, null);
		final View linearLayoutBg=pv.findViewById(R.id.linearLayoutBg);
		View.OnClickListener click = new OnClickListener() {
			@Override
			public void onClick(View v) {
				int vid = v.getId();
				switch (vid) {
				case R.id.textViewParise: {
					HashMap<String, String> hmap = new HashMap<String, String>();
					hmap.put("commentId", c.getId());
					getPariseTask(c).execute(hmap);
				}
					break;
				case R.id.textViewReplay: {// 回复,评论
					hidePop();
					Intent i = new Intent();
					i.setClass(TopicommentsActivity.this, CommentActivity.class);
					if ("0".equals(c.getParentId())) {// 最多只有2级评论，
						// 回复
						i.putExtra("comment", false);
						startActivityForResult(i, INT_GO_REPLY);
					} else {
						// 评论
						i.putExtra("comment", true);
						startActivityForResult(i, INT_GO_COMMENT);
					}

				}
					break;
				case R.id.textViewCopy: {
					String content = c.getContent();
					if (!StringUtils.isEmpty(content)) {
						Tool.copyClip(content, TopicommentsActivity.this);
						Tool.ToastShow(TopicommentsActivity.this, "内容复制成功！");
					}
					hidePop();
				}
					break;
				}
			}
		};

		TextView pt = (TextView) pv.findViewById(R.id.textViewParise);
		pt.setOnClickListener(click);
		pt.setText("赞" + c.getPraise());

		TextView rt = (TextView) pv.findViewById(R.id.textViewReplay);
		rt.setOnClickListener(click);

		TextView tr = (TextView) pv.findViewById(R.id.textViewCopy);
		tr.setOnClickListener(click);

		mPop = new PopupWindow(pv, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, true);
		mPop.setOutsideTouchable(true);
		mPop.setBackgroundDrawable(new BitmapDrawable());// 必须要有这个
		mPop.setFocusable(true);
		mPop.showAsDropDown(v);// view为Listview点击事件传过来的view.
		

		if (isBottom) {
			// 朝下
			int vheight = v.getHeight() + 50;
			linearLayoutBg.setBackgroundResource(R.drawable.bg_pop_back_down);
			mPop.showAsDropDown(v, 0, -vheight);
		} else {
			// 朝上
			linearLayoutBg.setBackgroundResource(R.drawable.bg_pop_back_up);
			mPop.showAsDropDown(v);
		}

		mPop.update();
		mPop.update();

	}

	private void showBottom(final boolean sayOrReplay, final Comment c) {
		final View v = findViewById(R.id.relativeLayoutReply);
		v.setVisibility(View.VISIBLE);
		TextView title = findTextViewById(R.id.textViewReplayTitle);
		title.setText(sayOrReplay ? "评论" : "回复");
		final EditText editContent = findEditTextById(R.id.editTextContentReply);
		Button btn = findButtonById(R.id.buttonReply);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String content = editContent.getText().toString();
				if (StringUtils.isEmpty(content) || content.length() > 200) {
					Tool.ToastShow(TopicommentsActivity.this, "请输入200字以内的内容！");
				} else {
					if (sayOrReplay) {
						// 评论
						comment(content);
					} else {
						// 回复
						reply(content, c);
					}
				}
			}
		});
	}

	/**
	 * @param reply
	 * @param coment
	 */
	private void reply(String reply, Comment coment) {
		// uid, commentId, articleId, commentContent);
		// getSubCommentTask().
		User u = App.getApp().getUser();
		if (null != u) {
			// uid, commentId, topicId, commentContent);
			HashMap<String, String> hmap = new HashMap<String, String>();
			hmap.put("uid", u.getUid());
			hmap.put("commentId", coment.getId());
			hmap.put("topicId", mTopic.getId());
			hmap.put("commentContent", reply);
			getSubCommentTask(coment, reply).execute(hmap);
		} else {
			Tool.startActivity(TopicommentsActivity.this, LoginActivity.class);
		}

	}

	/**
	 * 评论
	 */
	private void comment(String comment) {
		HashMap<String, String> hmap = new HashMap<String, String>();
		User u = App.getApp().getUser();
		if (null != u) {
			hmap.put("uid", App.getApp().getUser().getUid());
			hmap.put("topicId", mTopic.getId());
			hmap.put("commentContent", comment);
			getCommentTask().execute(hmap);
		} else {
			Tool.ToastShow(TopicommentsActivity.this, "请先登录!");
			Tool.startActivity(TopicommentsActivity.this, LoginActivity.class);
		}
	}

	/**
	 * 评论Task
	 * @return
	 */
	private BaseTask getCommentTask() {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						Comment cmt = (Comment) result.getData()[0];
						addNewComment(cmt, true);
						Tool.ToastShow(TopicommentsActivity.this, "评论成功！");
					} else {
						Tool.ToastShow(TopicommentsActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(TopicommentsActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.addParComment4Topic(TopicommentsActivity.this, paramMap);
				} catch (Exception e) {
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	private void replySuccess(NetResult result, Comment parentComment) {
		Comment cm = (Comment) result.getData()[0];
		parentComment.getSubComment().add(0, cm);
		addNewComment(cm, false);
		// uid, commentId, articleId, commentContent);
		// 回复成功
	}

	/**
	 * 回复Task
	 * 
	 * @return
	 */
	private BaseTask getSubCommentTask(final Comment coment, final String content) {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						replySuccess(result, coment);
					} else {
						Tool.ToastShow(TopicommentsActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(TopicommentsActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.addSubTopicComment(TopicommentsActivity.this, paramMap);
				} catch (Exception e) {
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	private LinearLayout addHotComments(ArrayList<Comment> cms) {
		LinearLayout lc = (LinearLayout) View.inflate(this, R.layout.header_hot_comment, null);
		if (!ListUtiles.isEmpty(cms)) {
			// 添加热门评论
			View hotDivider = View.inflate(this, R.layout.item_comments_divider_split, null);
			((TextView) hotDivider.findViewById(R.id.textViewIndicator)).setText("热门评论");
			lc.addView(hotDivider);

			for (int i = 0; i < cms.size(); i++) {
				Comment com = cms.get(i);
				View item = View.inflate(this, R.layout.item_article_comments, null);
				AsnycImageView asImg = (AsnycImageView) item.findViewById(R.id.asImageHeader);
				TextView textViewAuthor = (TextView) item.findViewById(R.id.textViewAuthor);
				User u = com.getUser();
				if (null != u) {
					asImg.setUrl(u.getHeadPortrait());
					textViewAuthor.setText(u.getName());
				}
				TextView textTime = (TextView) item.findViewById(R.id.textTime);
				textTime.setText(com.getTime());
				TextView textViewLocation = (TextView) item.findViewById(R.id.textViewLocation);
				TextView textViewGood = (TextView) item.findViewById(R.id.textViewGood);
				textViewGood.setText(com.getPraise() + "赞");
				TextView textViewComment = (TextView) item.findViewById(R.id.textViewComment);
				textViewComment.setText(com.getContent());
				lc.addView(item);
			}
		}
		// 添加最新评论
		View newDivider = View.inflate(this, R.layout.item_comments_divider_split, null);
		((TextView) newDivider.findViewById(R.id.textViewIndicator)).setText("最新评论");
		lc.addView(newDivider);
		return lc;
	}

	private void requestComments(int type, int offset) {
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("topicId", mTopic.getId());
		hmap.put("offset", String.valueOf(offset));
		hmap.put("limit", String.valueOf(page_size));
		getRequestTask(type).execute(hmap);
	}

	@Override
	public void onRefresh() {
		requestComments(INT_RTYPE_REFRESH, 0);
	}

	@Override
	public void onLoadMore() {
		requestComments(INT_RTYPE_LODMORE, mArrayList.size());
	}

	private void buildAdapter(int type, ArrayList<Comment> datas) {
		switch (type) {
		case INT_RTYPE_FIRST:// 首次请求
			// 首次请求
			mArrayList.clear();// 数据清零
			// if (!ListUtiles.isEmpty(ConsultDetailActivity.hotelCommentList))
			// {
			// mArrayList.add(createSplitComment(true));
			// mArrayList.addAll(ConsultDetailActivity.hotelCommentList);
			// }
			mArrayList.add(createSplitComment(false));
			mArrayList.addAll(datas);
			mAdapterConsult = new CommentsAdapter(this, loadSubList(mArrayList));
			listViewComments.setAdapter(mAdapterConsult);
			listViewComments.stopRefresh();
			listViewComments.setRefreshTime("刚刚");
			break;
		case INT_RTYPE_REFRESH:// 刷新
			mArrayList.clear();// 数据清零
			// if (!ListUtiles.isEmpty(ConsultDetailActivity.hotelCommentList))
			// {
			// mArrayList.add(createSplitComment(true));
			// mArrayList.addAll(ConsultDetailActivity.hotelCommentList);
			// }
			mArrayList.add(createSplitComment(false));
			mArrayList.addAll(datas);
			mAdapterConsult = new CommentsAdapter(this, loadSubList(mArrayList));
			listViewComments.setAdapter(mAdapterConsult);
			listViewComments.stopRefresh();
			listViewComments.setRefreshTime("刚刚");
			break;
		case INT_RTYPE_LODMORE:// 加载更多
			mArrayList.addAll(loadSubList(datas));
			listViewComments.stopLoadMore();
			mAdapterConsult.notifyDataSetChanged();
			break;
		default:
			break;
		}

	}

	/**
	 * list列表分割标志
	 * 
	 * @param isHot
	 */
	private Comment createSplitComment(boolean isHot) {
		Comment cmt = new Comment();
		cmt.setHot(isHot);
		cmt.setContent("");
		return cmt;
	}

	/**
	 * 抽出子评论，构建列表用
	 * 
	 * @param list
	 */
	private ArrayList<Comment> loadSubList(ArrayList<Comment> list) {
		mListTemp = new ArrayList<Comment>();
		for (int i = 0; i < list.size(); i++) {
			Comment journey = list.get(i);
			mListTemp.add(journey);
			ArrayList<Comment> sublist = journey.getSubComment();
			if (!ListUtiles.isEmpty(sublist)) {
				for (int j = 0; j < sublist.size(); j++) {
					Comment sub = sublist.get(j);
					mListTemp.add(sub);
				}
			}
		}
		return mListTemp;
	}

	private void addNewComment(Comment coment, boolean isComment) {
		if (coment.getParentId().equals("0") && isComment) {
			// 添加评论
			if (mListTemp.size() == 1) {
				mListTemp.add(1, coment);
			} else {
				for (int i = 0; i < mListTemp.size(); i++) {
					Comment temp = mListTemp.get(i);
					String tid = temp.getRelationId();
					if (!StringUtils.isEmpty(tid) && !temp.isHot() && tid.equals(coment.getRelationId())
							&& !StringUtils.isEmpty(temp.getContent())) {
						mListTemp.add(i, coment);
						mAdapterConsult.notifyDataSetChanged();
						LogUtil.i(App.tag, "评论成功");

						break;
					}
				}
			}
		} else {
			// 添加回复
			for (int i = 0; i < mListTemp.size(); i++) {// bug here
				Comment temp = mListTemp.get(i);
				String tid = temp.getId();
				if (!StringUtils.isEmpty(tid) && coment.getParentId().equals(tid)) {
					mListTemp.add(i + 1, coment);
					mAdapterConsult.notifyDataSetChanged();
					LogUtil.i(App.tag, "回复成功");
					break;
				}
			}
		}
	}

	private void hidePop() {
		if (null != mPop) {
			mPop.dismiss();
		}
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.buttonBack: {
			finish();
		}
			break;
		case R.id.buttonHideReplay: {
		}
			break;
		case R.id.linearLayoutBottomReply: {// 点击下面的说两句,发表评论
			Intent i = new Intent();
			i.setClass(TopicommentsActivity.this, CommentActivity.class);
			i.putExtra("comment", true);// 评论
			startActivityForResult(i, INT_GO_COMMENT);
		}
			break;
		default:
			break;
		}

	}

	private BaseTask getRequestTask(final int type) {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {

			@Override
			public void onPreCall() {
				if (1 == type) {
					showProgressDialogWithTask(mBaseTask);
				}
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						ArrayList<Comment> listData = (ArrayList<Comment>) result.getData()[0];
						buildAdapter(type, listData);
					} else {
						Tool.ToastShow(TopicommentsActivity.this, result.getMessage());
						if (type == INT_RTYPE_REFRESH) {
							listViewComments.stopRefresh();
						}
						if (type == INT_RTYPE_LODMORE) {
							listViewComments.stopRefresh();
						}
					}
				} else {
					Tool.ToastShow(TopicommentsActivity.this, R.string.error_net);
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult neteResult = null;
				try {
					neteResult = NetInterface.getTopicComments(TopicommentsActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return neteResult;
			}
		});
		return mBaseTask;
	}

	private BaseTask getPariseTask(final Comment cm) {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {
			@Override
			public void onPreCall() {
				super.onPreCall();
				showProgressDialogWithTask(mBaseTask);
			}

			@Override
			public void onFinish(NetResult result) {
				hideProgressDialogWithTask();
				if (null != result) {
					if (result.isSuccess()) {
						Tool.ToastShow(TopicommentsActivity.this, "赞+1");
						cm.addParse();
						hidePop();
						mAdapterConsult.notifyDataSetChanged();
					} else {
						Tool.ToastShow(TopicommentsActivity.this, result.getMessage());
					}
				} else {
					Tool.ToastShow(TopicommentsActivity.this, "网络错误!");
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult netResult = null;
				try {
					netResult = NetInterface.praise(TopicommentsActivity.this, paramMap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return netResult;
			}
		});
		return mBaseTask;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == INT_GO_REPLY && resultCode==RESULT_OK) {
			// 回复，i.putExtra("data", content);
			String replay = data.getStringExtra("data");
			reply(replay, mCommentCurrentReply);
		}

		if (requestCode == INT_GO_COMMENT&& resultCode==RESULT_OK) {
			String coment = data.getStringExtra("data");
			comment(coment);
		}
	}
}
